import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart'; // 导入listEquals所需的包

import '../../api/AlarmApi.dart';
import '../../api/DeviceApi.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../tools/widgets/my_app_bar.dart';

import '../../utils/toast_utils.dart';
import 'date_range_picker_component.dart'; // 导入组件

class DataSelectPage extends StatefulWidget {
  const DataSelectPage({
    super.key,
    this.camId,
    this.weekId,
    this.week,
    this.startTime,
    this.endTime,
  });

  final int? camId;
  final int? weekId;
  final String? week;
  final String? startTime;
  final String? endTime;

  @override
  State<DataSelectPage> createState() => _DataSelectPageState();
}

class _DataSelectPageState extends State<DataSelectPage> {
  final DeviceApi _deviceApi = DeviceApi();
  final AlarmApi _alarmApi = AlarmApi();
  late int _camId;
  late int _weekId;
  //类型 0-移动侦测，1-防区设置
  late int _weekIlk;
  // 定义模拟数据列表 - 初始化为空，将通过多选框动态更新
  List<String> mockDataList = [];

  // 存储选择的时间范围
  DateTime? _startTime;
  DateTime? _endTime;

  // 定义星期数据映射
  final Map<String, String> weekDayMap = {
    "1": "周一",
    "2": "周二",
    "3": "周三",
    "4": "周四",
    "5": "周五",
    "6": "周六",
    "7": "周日",
  };

  // 计算属性：根据mockDataList生成显示文本
  String get _displayWeekText {
    // 定义全周和周末的标准列表
    const allDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
    const weekendDays = {"周六", "周日"};

    // 将mockDataList转换为Set进行无顺序比较
    final selectedDays = mockDataList.toSet();

    // 判断是否包含所有7天
    if (selectedDays.containsAll(allDays)) {
      return AppLocale.text('d_meitian');
    }
    // 判断是否只包含周末
    else if (selectedDays.containsAll(weekendDays) && selectedDays.length == 2) {
      return AppLocale.text('d_zhoumo');
    }
    // 其他情况原样显示
    else {
      return mockDataList.join("  ");
    }
  }

  // @override
  // void initState() {
  //   super.initState();
  //   _camId = widget.camId!;
  //   _weekId = widget.weekId!;
  //   // 设置初始时间
  //   _startTime = DateTime(2021, 06, 21, 08, 00, 00);
  //   _endTime = DateTime(2021, 06, 23, 10, 00, 00);
  //
  //   // 初始化mockDataList - 可以根据需要设置默认选中项
  //   // 例如，默认选中周一到周五
  //   mockDataList = ["周一", "周二", "周三", "周四", "周五"];
  // }

  @override
  void initState() {
    super.initState();
    _camId = widget.camId!;
    _weekId = widget.weekId!;

    print(_camId);
    print(_weekId);
    print("asdfsdff");
    print(widget.week);
    print(widget.startTime);
    print(widget.endTime);

    // 初始化星期选择
    final week = widget.week;
    if (week != null) {
      mockDataList = week.split('、'); // 拆分"周一、周三、周四"为列表
    } else {
      mockDataList = ["周一", "周二", "周三", "周四", "周五"]; // 默认值
    }

    // 初始化时间（使用修复后的解析方法）
    _startTime = _parseTimeString(widget.startTime!) ?? DateTime(1970, 1, 1, 08, 00);
    _endTime = _parseTimeString(widget.endTime!) ?? DateTime(1970, 1, 1, 10, 00);
  }



  Future<void> _updateDataSelect() async {
    print("选择的时间范围: ${_startTime} - ${_endTime}");
    print("周: ${mockDataList}");

    final toUpdate = {
      "camId": _camId,
      "weekId": _weekId,
      "startTime" : _startTime.toString(),
      "endTime": _endTime.toString(),
      "week": mockDataList,
    };
    final response = await _alarmApi.updateDataSelect(toUpdate);
    if (response.code == 200) {
      setState(() {

      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }


// 辅助方法：将"HH:MM"格式的字符串转换为DateTime
  DateTime? _parseTimeString(String timeStr) {
    if (timeStr.isEmpty) return null;

    final parts = timeStr.split(':');
    if (parts.length != 2) return null;

    final hour = int.tryParse(parts[0]) ?? 0;
    int minute = int.tryParse(parts[1]) ?? 0;

    return DateTime(1970, 1, 1, hour, minute);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        // centerTitle: _weekId.toString(),
        centerTitle: AppLocale.text('d_shijianduan'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,

        showRightButton: true,
        rightButtonType: RightButtonType.text,
        rightButtonText: AppLocale.text('d_baocun'),
        rightButtonTextStyle: const TextStyle(
            color: Colors.blue,
            fontSize: 18
        ),
        onRightButtonPressed: () async {

          // 等待更新操作完成
          await _updateDataSelect();
          // 只有更新成功后才返回（可选，根据需求调整）
          Navigator.maybePop(context);
        },
      ),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            ItemView(
              width: double.infinity,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  const SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_chongfu'),
                    style: TextStyle(
                        fontSize: 15.0,
                        color: Colors.black
                    ),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  Text(
                    _displayWeekText, // 使用计算属性显示格式化后的文本
                    style: const TextStyle(
                        fontSize: 14.0,
                        color: Colors.black54
                    ),
                  ),
                  const Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.grey,
                    size: 14,
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {
                // 创建多选列表项，根据mockDataList设置初始选中状态
                List<BrnMultiSelectBottomPickerItem> items = [];
                weekDayMap.forEach((key, value) {
                  bool isChecked = mockDataList.contains(value);
                  items.add(BrnMultiSelectBottomPickerItem(key, value, isChecked: isChecked));
                });

                showModalBottomSheet(
                  context: context,
                  backgroundColor: Colors.transparent,
                  builder: (BuildContext dialogContext) {
                    // 移除嵌套的StatefulBuilder，直接使用主页面的setState
                    return BrnMultiSelectListPicker(
                      pickerTitleConfig: const BrnPickerTitleConfig(titleContent: "重复"),
                      items: items,
                      onItemClick: (_, index) {
                        if (items.where((element) => element.isChecked).length > 8) {
                          items[index].isChecked = false;
                          // 使用dialogContext查找最近的State并调用setState
                          // 注意：这种方式可能不适用于所有情况，建议使用回调
                        }
                      },
                      onSubmit: (List<BrnMultiSelectBottomPickerItem> data) {
                        // 直接调用主页面的setState方法
                        setState(() {
                          mockDataList = data
                              .where((item) => item.isChecked)
                              .map((item) => item.content)
                              .toList();
                        });

                        // 打印选中的项
                        print("选中的项: ${mockDataList.join("  ")}");

                        Navigator.of(context).pop();
                      },
                      onCancel: () {
                        Navigator.of(context).pop();
                      },
                    );
                  },
                );
              },
            ),

            const SizedBox(height: 20),

            // 使用新组件
            DateRangePickerComponent(
              title: "",
              width: 340,
              initialStartDateTime: _startTime,
              initialEndDateTime: _endTime,
              onChanged: (startDateTime, endDateTime) {
                setState(() {
                  _startTime = startDateTime;
                  _endTime = endDateTime;
                });
                // 使用格式化方法输出时间
                // if (startDateTime != null && endDateTime != null) {
                //   print("选择的时间范围: ${_formatTime(startDateTime)} - ${_formatTime(endDateTime)}");
                // }
              },
            ),
          ],
        ),
      ),
    );
  }

  // 添加格式化方法
  String _formatTime(DateTime dateTime) {
    return '${dateTime.hour.toString().padLeft(2, '0')}:'
        '${dateTime.minute.toString().padLeft(2, '0')}:'
        '${dateTime.second.toString().padLeft(2, '0')}';
  }
}